<?php

namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Model\PutForward;
use App\Model\UserBill;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PutForwardController extends Controller
{
    public function index(Request $request, PutForward $forward)
    {
        if ($request->has('name')){
            $forward->where('name', 'like', '%'.$request->input('name').'%');
        }
        if ($request->has('phone')){
            $forward->where('phone', '=', $request->input('phone'));
        }
        if (request()->has('time_start')){
            $forward->where('created_at', '>=', request('time_start'));
        }
        if (request()->has('time_end')){
            $forward->where('created_at', '<=', request('time_end'));
        }
        if (request()->has('time_start') and request()->has('time_end')){
            $forward->whereBetween('created_at', [request('time_start'), request('time_end')]);
        }
        return $this->renderJson($forward->paginate()->toArray());
    }

    public function forward($id, PutForward $forward)
    {
        $f = $forward->findOrFail($id);
        try {
            DB::transaction(function () use ($f) {

                $f->status = 1;
                $f->save();

                $log = new UserBill;
                $log->user_id = $f->user_id;
                $log->type = 5;
                $log->income_type = 0;
                $log->money = $f->amount;
                $log->save();
            });
            return $this->success();
        } catch (\Throwable $e) {
            return $this->error('修改失败');
        }
    }
}
